<template>
  <div>
    <el-table :data="tableData" row-key="id" ref="tableRef">
      <el-table-column   label="标题"   align="center"   prop="title" ></el-table-column>
      <el-table-column   label="文本"   align="center"   prop="text"  ></el-table-column>
    </el-table>
    <el-button @click="submit"> 提交</el-button>
  </div>
</template>

<script>
import Sortable from "sortablejs";
export default {
  name: "elTableDrag",
  data() {
    return {
      tableData: [
        {
          id: 1,
          title: "1",
          text: "1",
        },
        {
          id: 2,
          title: "2",
          text: "2",
        },
        {
          id: 3,
          title: "3",
          text: "3",
        },
        {
          id: 4,
          title: "4",
          text: "4",
        },
      ],
      newIndexList: [],
    };
  },

  methods: {
    // 更新排序
    initSortableList() {
      let el = this.$refs.tableRef.$el.querySelector(
        ".el-table__body-wrapper tbody"
      );
      //设置配置
      let _this = this;
      Sortable.create(el, {
        animation: 150,
        sort: true,
        draggable: ".el-table__row", // 设置可拖拽行的类名(el-table自带的类名)
        forceFallback: true,
        onEnd({ newIndex, oldIndex }) {
          let currRow = _this.newIndexList.splice(oldIndex, 1)[0];
          _this.newIndexList.splice(newIndex, 0, currRow);
        },
      });
    },
    submit(){
      let arr = []
      this.newIndexList.forEach(item=>arr.push(this.tableData.find(item2=>  item2.id == item)))
      this.tableData = JSON.parse(JSON.stringify(arr))
    }
  },

  watch: {},
  computed: {
    Sortable,
  },

  created() {},
  mounted() {
    // 复制原Table的id按循序存储newIndexList中,
    // 每一次调整位置会对newIndexList进行位置调整。
    this.tableData.forEach((item) => this.newIndexList.push(item.id));
    this.initSortableList();

    // //阻止火狐拖拽新建新页面
    document.body.addEventListener("drop", (event) => {
      event.preventDefault();
      event.stopPropagation();
    }, false);
  },
  beforeDestroy() {},
};
</script>

<style scoped lang="less">
</style>